package com.cuitrip.util;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import com.lab.logtrack.AppLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ak on 15/11/12.
 */
public class PackageUtil {

    /**
     * 判断当前界面是否是虾米音乐
     */
    public static boolean isOurApp(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        if (rti == null || rti.size() == 0 ){
            return false;
        }
        ComponentName activity = rti.get(0).topActivity;
        if (activity == null){
            return false;
        }
        return activity.getPackageName().equals(context.getPackageName());
    }

    /**
     * 判断当前界面是否是桌面
     */
    public boolean isHome(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        try {
            return getHomes(context).contains(rti.get(0).topActivity.getPackageName());
        } catch (Exception e) {
            AppLog.w(e.getMessage());
        }
        return true;
    }

    /**
     * 获得属于桌面的应用的应用包名称
     *
     * @return 返回包含所有包名的字符串列表
     */
    private List<String> getHomes(Context context) {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        try{
            List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo ri : resolveInfo) {
                names.add(ri.activityInfo.packageName);
            }
        }catch (Exception e){
            AppLog.w(e.getMessage());
        }
        return names;
    }

}
